package cn.itcast.controller;

import cn.itcast.common.R;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * @Author GuoMingXi @Email guomingxi2018@163.com
 * @Create 2022/6/1 15:39
 * @Version V1.0
 */
@RestController
@RequestMapping("/common")
public class PicController  extends BaseController{
    @Value("${reggie.basepath}")
    private String basePath;

    @PostMapping("/upload")
    @SneakyThrows
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName=UUID.randomUUID()+suffix;
        //当路径不存在时，创建文件夹
        File dir = new File(basePath);
        if (!dir.exists()){
           dir.mkdirs();
        }
        file.transferTo(new File(basePath,fileName));
        return R.success(fileName);
    }
    @GetMapping("/download")
    @SneakyThrows
    public void download(String name){
        FileInputStream fileInputStream = new FileInputStream(new File(basePath, name));
        IOUtils.copy(fileInputStream,response.getOutputStream());

    }
}
